#!/sbin/openrc-run

name=snac
description="Snac is an ActivityPub server written in portable C"

: ${SNAC_DATA:="/var/lib/snac/data"}

extra_stopped_commands="setup purge"
extra_commands="adduser deluser resetpwd"
description_setup="Setup the database at ${SNAC_DATA}"
description_purge="Purge old data from ${SNAC_DATA}"
description_adduser="Add a new user to ${SNAC_DATA}"
description_deluser="Delete a user from ${SNAC_DATA}"
description_resetpwd="Reset password of user in ${SNAC_DATA}"

command="/usr/bin/snac"
command_args="httpd ${SNAC_DATA}"
command_background="yes"
command_user="snac:snac"
pidfile="/run/${RC_SVCNAME}.pid"
error_log="/var/log/snac.log"

depend() {
	need localmount net
	after firewall
}

ensure_db_exists() {
	if [ ! -f "${SNAC_DATA}/server.json" ]; then
		setup || return 1
	fi

	return 0
}

start_pre() {
	ensure_db_exists || return 1

	checkpath -f -m 0640 -o "$command_user" "$error_log"
	checkpath -d -m 0750 -o "$command_user" "${SNAC_DATA}"
}

setup() {
	snac_exec init
}

purge() {
	ensure_db_exists || return 1

	ebegin "Purging old data from ${SNAC_DATA}"
	snac_exec purge
	eend $?
}

adduser() {
	ensure_db_exists || return 1

	snac_exec adduser
}

deluser() {
	ensure_db_exists || return 1

	read -p "Username: " username

	snac_exec deluser $username
}

resetpwd() {
	ensure_db_exists || return 1

	read -p "Username: " username

	snac_exec resetpwd $username
}

snac_exec() {
	local subcmd="$1"
	shift

	start-stop-daemon --exec "$command" --user "$command_user" \
		-- $subcmd "${SNAC_DATA}" $*
}
